<?php

namespace App\Repositories\Manage;

use App\Models\DailyMenu;
use App\Models\MenuProductMapping;
use App\Models\Product;
use App\Models\ProductCategory;
use App\Models\Supplier;

class ProductCategoryRepository
{
    public function getProductsByMenuId($menu_id = 0)
    {
        if (!$menu_id)
            return [];

        $shop_id = DailyMenu::query()->where(['id' => $menu_id])->value("shop_id");
        $selectProductIds = MenuProductMapping::where([
            'menu_id' => $menu_id,
            'status' => 1
        ])
            ->pluck('product_id')
            ->toArray();

        $productCategtoryList = ProductCategory::query()
            ->where([
                'is_delete' => 2,
                'status' => 1,
//                'is_special' => 0,
                'shop_id' => $shop_id
            ])
            ->orderBy("sort", "asc")
            ->orderBy("id", "asc")
            ->get(['id', 'title'])
            ->toArray();

        foreach ($productCategtoryList as $k => &$v) {

            $v['products'] = Product::query()
                ->where([
                    'status' => 1,
                    'category_id' => $v['id'],
                    'shop_id' => $shop_id,
//                    'is_delete' => 2,
                ])
                ->when(isset($selectProductIds), function ($q) use ($selectProductIds) {
                    $q->whereNotIn("id", $selectProductIds);
                })->get(array_filter(explode(",", "id,title,thumb,price,product_class")));

            if (!isset($v['products'])) {
                unset($productCategtoryList[$k]);
            }
        }

        return $productCategtoryList;
    }

    /**
     * @param array $filter
     * @param int $pageNum
     * @param int $pageSize
     * @return array
     */
    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = ProductCategory::query()
            ->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("title", "like", "%{$filter['keywords']}%");
            })
            ->when(!empty($filter['shop_id']), function ($query) use ($filter) {
                return $query->where("shop_id", intval($filter['shop_id']));
            })
//            ->orderBy("sort", "desc")
            ->orderBy("id", "desc")
            ->paginate($pageSize, ["*"], null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);
        foreach ($res['items'] as $k => &$v) {
            $v['shop_title'] = Supplier::query()->where(['id' => $v['shop_id']])->value("title");
        }

        return $res;
    }

    /**
     * 批量删除
     * @param null $ids
     */
    public function batchDelete($ids = null)
    {
        if (intval($ids)) {
            ProductCategory::query()->where(['id' => $ids])->delete();
        } else {
            ProductCategory::query()->whereIn("id", $ids)->delete();
        }

        return retSuc([], "删除成功");
    }

    public function saveOrUpdate($data = [], $id = 0)
    {
        if (!empty($data['id']))
            unset($data['id']);

        if (intval($id)) {
            ProductCategory::where("id", $id)->update($data);
            return $id;
        } else {
            $res = ProductCategory::create($data);
            return $res['id'] ?? "";
        }
    }

    public function getOne(int $id)
    {
        return ProductCategory::query()->where(['id' => $id])->first();
    }

    /**
     * @param int $shop_id
     * @return array
     */
    public function getOptions(int $shop_id = 0)
    {
        return ProductCategory::query()->where('id', '>', 0)
            ->when($shop_id, function ($q) use ($shop_id) {
                return $q->where('shop_id', $shop_id);
            })
            ->where(['status' => 1])
            ->orderBy("id", 'desc')
            ->get(['id', 'title'])
            ->toArray();
    }

    /**
     * 检查重名
     * @param int $id
     * @param null $title
     * @return bool|int
     */
    public function checkExistByTitle(int $id, $title = null, int $shop_id = 0)
    {
        if (empty($title))
            return true;

        return ProductCategory::query()->where('title', $title)
            ->when($id, function ($q) use ($id) {
                return $q->where('id', '!=', $id);
            })
            ->where('shop_id', $shop_id)
            ->count('id');
    }

}
